﻿
using ARchGL.Platform.Electrocar.Application.Enum;
using ARchGL.Platform.Electrocar.Application.ViewDtos;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using CellType = NPOI.SS.UserModel.CellType;

namespace ARchGL.Platform.Electrocar.Application.Utils
{
    /// <summary>
    /// 
    /// </summary>
    public class ExcelHelper
    {
        /// <summary>
        /// 将数据导出为Excel文件
        /// </summary>
        /// <param name="name">文件名</param>
        /// <param name="strList">数据</param>
        /// <param name="path">路径，默认D盘根目录</param>
        /// <returns></returns>
        public string ExportExcel(string name, List<string[]> strList, string path)
        {
            path = SystemHelper.GetContentRootFolder();
            var documentPath = string.Format($"{path}{name}.xlsx");
            var spreadsheetDocument = SpreadsheetDocument.Create(documentPath, SpreadsheetDocumentType.Workbook);
            var workbookpart = spreadsheetDocument.AddWorkbookPart();
            workbookpart.Workbook = new Workbook();
            var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
            worksheetPart.Worksheet = new Worksheet(new SheetData());
            var sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild(new Sheets());
            var sheet = new Sheet() { Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "Sheet1" };
            sheets.Append(sheet);
            var sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();
            foreach (var item in strList)
            {
                var row = new Row();
                foreach (var str in item)
                {
                    var dataCell = new Cell
                    {
                        CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(str),
                        DataType = new EnumValue<CellValues>(CellValues.String)
                    };
                    row.AppendChild(dataCell);
                }
                sheetData.Append(row);
            }

            workbookpart.Workbook.Save();
            spreadsheetDocument.Close();
            return documentPath;
        }

        /// <summary>
        /// 读取Excel文件(DocumentOpenXML)
        /// </summary>
        /// <param name="path">文件路径</param>
        public List<string[]> ImportExcel(string path)
        {
            using (SpreadsheetDocument doc = SpreadsheetDocument.Open(path, false))
            {
                var wbPart = doc.WorkbookPart;
                var tablePart = wbPart.SharedStringTablePart;
                var mysheet = (Sheet)doc.WorkbookPart.Workbook.Sheets.ChildElements.FirstOrDefault();
                var worksheet = ((WorksheetPart)wbPart.GetPartById(mysheet.Id));
                var sheetData = worksheet.Worksheet.GetFirstChild<SheetData>();
                var strList = new List<string[]>();
                var arrayList = new ArrayList();
                foreach (var row in sheetData.ChildElements)
                {
                    foreach (var cell in (row as Row).ChildElements)
                    {
                        var cellValue = (cell as Cell).CellValue;
                        if (cellValue != null)
                        {
                            arrayList.Add(GetValue((cell as Cell), tablePart));
                        }
                    }
                    var arrString = (string[])arrayList.ToArray(typeof(string));
                    strList.Add(arrString);
                    arrayList.Clear();
                    arrString = null;
                }
                return strList;
            }
        }

        /// <summary>
        /// 读取Excel文件(NPOI) 
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public List<string[]> ImportExcel_NPOI(string path)
        {
            var arrayList = new ArrayList();
            var strList = new List<string[]>();
            var dt = new DataTable();
            IWorkbook workbook;
            var fileExt = Path.GetExtension(path).ToLower();
            using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                //XSSFWorkbook 适用XLSX格式，HSSFWorkbook 适用XLS格式
                if (fileExt == ".xlsx")
                {
                    workbook = new XSSFWorkbook(fs);
                }
                else if (fileExt == ".xls")
                {
                    workbook = new HSSFWorkbook(fs);
                }
                else
                {
                    workbook = null;
                }

                if (workbook == null) { return null; }


                var sheet = workbook.GetSheetAt(0);

                //表头  
                var header = sheet.GetRow(sheet.FirstRowNum);
                var columns = new List<int>();
                for (int i = 0; i < header.LastCellNum; i++)
                {
                    var obj = GetValueType(header.GetCell(i));
                    if (obj == null || obj.ToString() == string.Empty)
                    {
                        dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
                    }
                    else
                        dt.Columns.Add(new DataColumn(obj.ToString()));
                    columns.Add(i);
                    arrayList.Add(obj.ToString());
                }

                var arrString = (string[])arrayList.ToArray(typeof(string));
                strList.Add(arrString);
                arrayList.Clear();
                arrString = null;

                //数据  
                for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
                {
                    var dr = dt.NewRow();
                    var hasValue = false;
                    foreach (int j in columns)
                    {
                        dr[j] = GetValueType(sheet.GetRow(i).GetCell(j));
                        if (dr[j] != null && dr[j].ToString() != string.Empty)
                        {
                            hasValue = true;
                            arrayList.Add(dr[j]);
                        }
                    }
                    if (hasValue)
                    {
                        arrString = (string[])arrayList.ToArray(typeof(string));
                        strList.Add(arrString);
                        arrayList.Clear();
                        arrString = null;
                    }
                }
            }
            return strList;
        }

        /// <summary>
        /// 获取单元格类型
        /// </summary>
        /// <param name="cell"></param>
        /// <returns></returns>
        private static object GetValueType(ICell cell)
        {
            if (cell == null)
                return null;
            switch (cell.CellType)
            {
                case CellType.Blank: //BLANK:  
                    return null;
                case CellType.Boolean: //BOOLEAN:  
                    return cell.BooleanCellValue;
                case CellType.Numeric: //NUMERIC:  
                    return cell.NumericCellValue;
                case CellType.String: //STRING:  
                    return cell.StringCellValue;
                case CellType.Error: //ERROR:  
                    return cell.ErrorCellValue;
                case CellType.Formula: //FORMULA:  
                default:
                    return "=" + cell.CellFormula;
            }
        }

        /// <summary>
        /// 读取s类型的列（SharedStringTable类型），它的值是存储在子元素内的。
        /// </summary>
        /// <param name="cell">单元格</param>
        /// <param name="stringTablePart">WorkbookPart.SharedStringTablePart</param>
        /// <returns></returns>
        public static String GetValue(Cell cell, SharedStringTablePart stringTablePart)
        {
            if (cell.ChildElements.Count == 0)

                return null;

            String value = cell.CellValue.InnerText;


            if ((cell.DataType != null) && (cell.DataType == CellValues.SharedString))

                value = stringTablePart.SharedStringTable

                .ChildElements[Int32.Parse(value)]

                .InnerText;

            return value;

        }
    }
}
